import config from '../config'
import axios from 'axios'
/**
 * 清除本地token
 */
export function clearToken() {
  localStorage.removeItem(config.tokenTableName)
}

export function setTokenWithExpire(data) {
  const now = new Date()
  const refresh_expire_at = now.getTime() + data.refresh_token_expires - config.refresh_offset
  const expire_at = now.getTime() + data.access_token_expires - config.refresh_offset
  const item = {
    refresh_expire_at,
    expire_at,
    ...data
  }
  localStorage.removeItem(config.tokenTableName)
  localStorage.setItem(config.tokenTableName, JSON.stringify(item))
}

export async function getTokenAsync() {
  const itemStr = localStorage.getItem(config.tokenTableName)
  if (!itemStr) {
    return null
  }
  const item = JSON.parse(itemStr)
  const now = new Date()
  //token and refresh token expired
  if (now.getTime() > item.expire_at && now.getTime() > item.refresh_expire_at) {
    localStorage.removeItem(config.tokenTableName)
    return null
  }
  //refresh token when expired
  if (now.getTime() > item.expire_at && now.getTime() < item.refresh_expire_at) {
    try {
      const res = await refreshToken(item.refresh_token)
      setTokenWithExpire(res.data)
      return res.data.access_token
    } catch (error) {
      console.error(error)
      return null
    }
  }

  return item.access_token
}

// 实时刷新token
export function refreshToken(token) {
  const request = axios.create({
    baseURL: config.baseURL,
    timeout: config.timeout,
    headers: {
      Accept: 'application/json, text/plain, application/octet-stream, */*',
      Authorization: 'Bearer ' + token
    }
  })
  return request({
    url: '/api/auth/refreshToken',
    method: 'post'
  })
}
